package com.opencee.cloud.uaa.handler;

import com.opencee.common.exception.DefaultWebExceptionAdvice;
import com.opencee.common.model.ApiErrorResult;
import com.opencee.common.utils.WebUtil;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yadu
 */
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    public CustomAuthenticationFailureHandler() {
    }

    public CustomAuthenticationFailureHandler(String defaultFailureUrl) {
        super(defaultFailureUrl);
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (WebUtil.acceptHasJson(request)) {
            ResponseEntity<ApiErrorResult> entity = DefaultWebExceptionAdvice.resolveException(exception, request.getRequestURI());
            WebUtil.writeJson(response, entity.getBody());
        } else {
            super.onAuthenticationFailure(request, response, exception);
        }
    }
}
